import { create } from 'zustand'
import { weatherService } from '../services/weatherService'
import { cacheManager } from '../utils/cache'
import { WEATHER_ICONS } from '../utils/constants'

const useWeatherStore = create((set, get) => ({
  // 状态
  currentWeather: null,
  weatherForecast: null,
  loading: false,
  error: null,
  searchHistory: [],

  // 初始化时从缓存加载历史记录
  initHistory: () => {
    const cachedHistory = cacheManager.get('search_history')
    if (cachedHistory) {
      set({ searchHistory: cachedHistory })
    }
  },

  // 获取天气数据
  fetchWeather: async (city) => {
    if (!city.trim()) {
      set({ error: '请输入城市名称' })
      return
    }

    set({ loading: true, error: null })

    try {
      // 检查缓存
      const cachedData = cacheManager.getWeatherCache(city)
      if (cachedData) {
        set({
          currentWeather: cachedData.current,
          weatherForecast: cachedData.forecast,
          loading: false
        })
        // 添加到历史记录
        get().addToSearchHistory(city)
        return
      }

      // 并行请求实时天气和预报
      const [currentResult, forecastResult] = await Promise.all([
        weatherService.getCurrentWeather(city),
        weatherService.getWeatherForecast(city)
      ])

      if (currentResult.success && forecastResult.success) {
        const weatherData = {
          current: {
            ...currentResult.data,
            icon: WEATHER_ICONS[currentResult.data.weather] || WEATHER_ICONS['默认']
          },
          forecast: {
            ...forecastResult.data,
            casts: forecastResult.data.casts.map(cast => ({
              ...cast,
              icon: WEATHER_ICONS[cast.dayweather] || WEATHER_ICONS['默认']
            }))
          }
        }

        // 设置缓存
        cacheManager.setWeatherCache(city, weatherData)

        // 更新状态
        set({
          currentWeather: weatherData.current,
          weatherForecast: weatherData.forecast,
          loading: false,
          error: null
        })

        // 添加到搜索历史
        get().addToSearchHistory(city)
      } else {
        set({
          error: currentResult.error || forecastResult.error,
          loading: false
        })
      }
    } catch (error) {
      set({
        error: '获取天气信息失败',
        loading: false
      })
    }
  },

  // 添加到搜索历史
  addToSearchHistory: (city) => {
    set((state) => {
      // 过滤掉重复的城市，把最新的放在最前面
      const newHistory = [
        city, 
        ...state.searchHistory.filter(item => item !== city)
      ].slice(0, 8) // 最多保存8条记录
      
      // 保存到缓存
      cacheManager.set('search_history', newHistory, 7 * 24 * 60 * 60 * 1000) // 7天缓存
      
      return { searchHistory: newHistory }
    })
  },

  // 删除单个历史记录
  removeFromSearchHistory: (city) => {
    set((state) => {
      const newHistory = state.searchHistory.filter(item => item !== city)
      // 更新缓存
      cacheManager.set('search_history', newHistory, 7 * 24 * 60 * 60 * 1000)
      return { searchHistory: newHistory }
    })
  },

  // 清空所有历史记录
  clearSearchHistory: () => {
    set({ searchHistory: [] })
    cacheManager.remove('search_history')
  },

  // 清除错误
  clearError: () => set({ error: null }),

  // 清除数据
  clearData: () => set({ currentWeather: null, weatherForecast: null })
}))

export default useWeatherStore